package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public ResultInfo login(String username, String password) {

        //1. 调用mapper,根据username查询;如果查询不到,返回错误提示
        Employee employee = employeeMapper.findByUsername(username);
        if(employee==null){
            return ResultInfo.error("用户不存在");
        }

        //2. 将传入的password进行加密,跟查询到的password进行比对
        String passwordWithMd5 = SecureUtil.md5(password);
        if(!StringUtils.equals(passwordWithMd5,employee.getPassword())){
            return ResultInfo.error("您输入的密码不正确");
        }

        //3.查看用户的status是否为0,禁用状态
        if(employee.getStatus()==Employee.STATUS_DISABLE){
            return ResultInfo.error("当前用户已被禁用");
        }

        //4.登陆成功,返回Employee信息
        return ResultInfo.success(employee);
    }

    @Override
    public List<Employee> findByName(String name) {

        return employeeMapper.findByName(name);
    }

    @Override
    public void save(Employee employee) {
        //补齐参数
        //雪花算法,生成一个唯一的lang值
        employee.setId(IdUtil.getSnowflake(1,1).nextId());//主键(不自动增加,需要手动赋予)
        employee.setPassword(SecureUtil.md5("123"));//设置123为默认密码
        employee.setStatus(Employee.STATUS_ENABLE);//设置默认状态(虽然SQL里有默认值,但是传null会报错,需要设置)
        /*//t/odo  临时写死,后期需要优化
        employee.setCreateTime(new Date());
        employee.setUpdateTime(new Date());

        //TO/DO 临时写死,后期要从session中获取到当前操作用户
        employee.setUpdateUser(1L);
        employee.setCreateUser(1L);*/

        //调用mapper保存
        employeeMapper.save(employee);
    }

    @Override
    public Employee findById(long id) {
        return employeeMapper.findById(id);
    }

    @Override
    public void update(Employee employee) {
       /* //补齐参数
        employee.setUpdateTime(new Date());
        employee.setUpdateUser(1L);*/
        //调用mapper进行更新
        employeeMapper.update(employee);
    }
}
